package com.xxlie.spring.interceptor;

import com.xxlie.spring.common.Constants;
import com.xxlie.spring.common.UserContext;
import com.xxlie.spring.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @author Cedric
 * 登录验证拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (Objects.isNull(request.getSession().getAttribute(Constants.USER_SESSION_KEY))) {
            System.out.println("Current user is not logged in.");
            response.sendRedirect("/goLogin");
            return false;
        }
        User user = (User) request.getSession().getAttribute(Constants.USER_SESSION_KEY);
        UserContext.setCurrentUser(user);
        System.out.println("preHandle, login user=" + user.toString());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion");
    }

}